import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { getList, getUsers, getWeather } from './service';

export interface userModelState {
  name: string;
  weatherData: object;
  userData: object;
}

export interface userModelType {
  namespace: 'user';
  state: userModelState;
  effects: {
    getWeather: Effect;
    query: Effect;
    getRemote: Effect;
    getUser: Effect;
  };
  reducers: {
    save: Reducer<userModelState>;
    saveWeather: Reducer<userModelState>;
    getList: Reducer<userModelState>;
    getUserData: Reducer<userModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<userModelState>;
  };
  subscriptions: { setup: Subscription };
}

const userModel: userModelType = {
  namespace: 'user',

  state: {
    name: '',
    weatherData: {},
    userData: {},
  },
  // 异步
  effects: {
    // 获取实时天气
    *getWeather({ payload }, { call, put }) {
      const res = yield call(getWeather, { city: payload });
      const { status, data } = res;
      if (status === 1000) {
        yield put({
          type: 'save',
          payload: { weatherData: data },
        });
      }
    },
    *query({ payload }, { call, put }) {},
    *getRemote({ payload }, { call, put }) {
      const data = yield call(getList);
      yield put({
        type: 'getList',
        payload: {
          data,
        },
      });
    },
    *getUser({ payload }, { call, put }) {
      const user = yield call(getUsers);
      console.log(user, 'user');
      yield put({
        type: 'save',
        payload: user,
      });
    },
  },
  // 同步
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 保存天气数据
    saveWeather(state, action) {
      return action.payload;
    },
    getList(state, { payload }) {
      return payload;
    },
    getUserData(state, action) {
      console.log(state, 'state');
      console.log(action, 'action');
      return action.payload;
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  // 订阅
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/user') {
          dispatch({
            type: 'save',
          });
        }
      });
    },
  },
};

export default userModel;
